package com.me.blood.frag;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.chart.Chart2Fragment;
import com.me.bean.Xt;
import com.me.blood.R;
import com.me.blood.activity.BaseActivity;
import com.me.blood.activity.InputActivity;
import com.me.blood.activity.XtHistory;
import com.me.blood.databinding.FragHomeBinding;
import com.me.db.DBListener;
import com.me.db.XtDao;
import com.me.utils.Utils;
import com.me.ad.ADType;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import lecho.lib.hellocharts.listener.LineChartOnValueSelectListener;
import lecho.lib.hellocharts.model.PointValue;

public class HomeFragment extends BaseTabFragment {

    FragHomeBinding binding;
    int type = 0;
    List<TextView> types = new ArrayList<>();
    long selectDay;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragHomeBinding.inflate(inflater, container, false);
        binding.top.setPadding(0, Utils.getStatusBarHeight(getActivity()) + Utils.dp2Px(getActivity(), 13), 0, Utils.dp2Px(getActivity(), 35));
        binding.ratio.setRatio(0.7f);
        selectDay = Calendar.getInstance().getTimeInMillis();
        setDay();
        types.add(binding.day);
        types.add(binding.week);
        types.add(binding.month);
        for (int i = 0; i < types.size(); i++) {
            int j = i;
            types.get(i).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    updateType(j);
                }
            });
        }
        binding.add.setOnClickListener(v -> {
            ((BaseActivity) getActivity()).getReward(ADType.HOME_REWARD, new Runnable() {
                @Override
                public void run() {
                    Intent i = new Intent(getActivity(), InputActivity.class);
                    startActivityForResult(i, 1);
                }
            });
        });
        binding.today.setOnClickListener(v -> showCalendar());
        binding.left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar c = Calendar.getInstance();
                c.setTimeInMillis(selectDay);
                c.add(Calendar.DAY_OF_MONTH, -1);
                selectDay = c.getTimeInMillis();
                setDay();
            }
        });
        binding.right.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Calendar c = Calendar.getInstance();
                c.setTimeInMillis(selectDay);
                c.add(Calendar.DAY_OF_MONTH, 1);
                selectDay = c.getTimeInMillis();
                setDay();
            }
        });
        binding.history.setOnClickListener(view -> {
            Intent i = new Intent(getActivity(), XtHistory.class);
            startActivityForResult(i, 2);
        });
        updateLast();
        getData();
        return binding.getRoot();
    }

    private void updateLast() {
        new XtDao().getLast(new DBListener() {
            @Override
            public void onResult(boolean bo, String msg, Object result) {
                h.post(new Runnable() {
                    @Override
                    public void run() {
                        if (result instanceof Xt) {
                            String s = Utils.getValue(((Xt) result).value);
                            binding.last.setText(s);
                            binding.icon.setBackgroundResource(Utils.getStateRes((Xt) result));
                        } else {
                            binding.last.setText("--");
                            binding.icon.setBackgroundColor(Color.TRANSPARENT);
                        }
                    }
                });
            }
        });
        new XtDao().getOneDay(Utils.getDay(System.currentTimeMillis()), new DBListener() {
            @Override
            public void onResult(boolean bo, String msg, Object result) {
                h.post(new Runnable() {
                    @Override
                    public void run() {
                        if (result instanceof List && !((List<?>) result).isEmpty()) {
                            float v = 0;
                            for (Xt item : (List<Xt>) result) {
                                v += item.value;
                            }
                            v /= ((List<?>) result).size();
                            Xt item = new Xt();
                            item.value = v;
                            binding.pj.setText(Utils.getValue(item.value));
                            binding.icon2.setBackgroundResource(Utils.getStateRes(item));
                        } else {
                            binding.icon2.setBackgroundColor(Color.TRANSPARENT);
                            binding.pj.setText("--");
                        }
                    }
                });
            }
        });
    }

    private void showCalendar() {
        CalendarDlg dlg = new CalendarDlg();
        dlg.setOnDismissListener(new BaseDialogFragment.OnDismissListener() {
            @Override
            public void onDismiss(boolean isOk, Object value) {
                if (isOk && value instanceof Date) {
                    Calendar c = Calendar.getInstance();
                    c.setTime((Date) value);
                    selectDay = c.getTimeInMillis();
                    setDay();
                    getData();
                }
            }
        });
        dlg.show(getChildFragmentManager(), "cal");
    }

    private void updateType(int i) {
        if (type == i) {
            return;
        }
        type = i;
        for (int j = 0; j < types.size(); j++) {
            if (i == j) {
                types.get(j).setTextColor(0xff0FB7A2);
            } else {
                types.get(j).setTextColor(0xff3a3a3a);
            }
        }
        getData();
    }

    private void setDay() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
        String createDate = formatter.format(selectDay);   //格式转换
        String day = dateToWeek(createDate);
        createDate = createDate.substring(createDate.indexOf("年") + 1);
        createDate = createDate + " " + day;
        binding.today.setText(createDate);

        getData();
    }

    public static String dateToWeek(String datetime) {
        SimpleDateFormat f = new SimpleDateFormat("yyyy年MM月dd日");
        String[] weekDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
        Calendar cal = Calendar.getInstance(); // 获得一个日历
        Date datet = null;
        try {
            datet = f.parse(datetime);
            cal.setTime(datet);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1; // 指示一个星期中的某天。
        if (w < 0) w = 0;
        return weekDays[w];
    }

    public static String dateToWeek(long time) {
        String[] weekDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
        Calendar cal = Calendar.getInstance(); // 获得一个日历
        cal.setTimeInMillis(time);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1; // 指示一个星期中的某天。
        if (w < 0) w = 0;
        return weekDays[w];
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
            getData();
        } else if (requestCode == 2) {
            getData();
        }
    }

    @Override
    protected ADType getXpType() {
        return ADType.HOME_XP;
    }

    @Override
    public void onResume() {
        super.onResume();
        updateLast();
    }

    private String getSelectDay() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
        String createDate = formatter.format(selectDay);   //格式转换
        return createDate;
    }

    private void getData() {
        if (type == 0) {
            new XtDao().getOneDay(getSelectDay(), new DBListener() {
                @Override
                public void onResult(boolean bo, String msg, Object result) {
                    if (result instanceof List) {
                        h.post(() -> update((List<Xt>) result));
                    } else {
                        h.post(() -> update(Collections.emptyList()));
                    }
                }
            });
        } else if (type == 1) {
            new XtDao().getWeek(getSelectDay(), new DBListener() {
                @Override
                public void onResult(boolean bo, String msg, Object result) {
                    if (result instanceof List) {
                        h.post(() -> update((List<Xt>) result));
                    } else {
                        h.post(() -> update(Collections.emptyList()));
                    }
                }
            });
        } else if (type == 2) {
            new XtDao().getMonth(getSelectDay(), new DBListener() {
                @Override
                public void onResult(boolean bo, String msg, Object result) {
                    if (result instanceof List) {
                        h.post(() -> update((List<Xt>) result));
                    } else {
                        h.post(() -> update(Collections.emptyList()));
                    }
                }
            });
        }
    }

    private void update(List<Xt> list) {
        if (list == null || list.isEmpty()) {
            binding.time.setText("--");
            binding.value.setText("--");
        }
        Chart2Fragment f = new Chart2Fragment();
        f.setData(list, type, getSelectDay(), new LineChartOnValueSelectListener() {
            @Override
            public void onValueSelected(int lineIndex, int pointIndex, PointValue value) {
                if (type == 0) {
                    StringBuffer sb = new StringBuffer();
                    int h = (int) value.getX();
                    int m = (int) ((value.getX() - h) * 60);
                    if (h < 0) {
                        sb.append("0");
                    }
                    sb.append(h).append(":");
                    if (m < 10) {
                        sb.append("0");
                    }
                    sb.append(m);
                    binding.time.setText(sb.toString());
                } else {
                    String s = f.getLabel((int) value.getX() - 1);
                    binding.time.setText(s);
                }
                DecimalFormat decimalFormat = new DecimalFormat("#0.0"); // 设置格式化模式为保留两位小数
                String result = decimalFormat.format(value.getY());
                binding.value.setText(result);
            }

            @Override
            public void onValueDeselected() {

            }
        });
        replaceFragment(R.id.ratio, f);
    }
}
